import axios from 'axios'
import { blobSaveFile } from './index'
import { getAppId, getAuthorization } from './auth'
import { Notification } from 'element-ui'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  withCredentials: true,
  // baseURL: '',
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  },
  timeout: 30000 // 请求超时时间
})

service.interceptors.request.use(
  config => {
    config.headers.AppId = getAppId()
    config.headers.Authorization = getAuthorization()
    return config
  },
  error => {
    Promise.reject(error)
  }
)

let responseErrorNoticed = null

// respone拦截器
service.interceptors.response.use(
  response => {
    const data = response.data
    const code = data.code
    if (response.config.responseType === 'blob') {
      // 导出文件，而响应是一个json类型
      if (response.data.type === 'application/json') {
        Notification({
          title: '未知错误',
          type: 'error',
          duration: 2000
        })
        return Promise.reject(response)
      }
      response.fileName = decodeURI(response.headers['content-disposition'].slice('attachment;filename='.length))
      return response
    }
    if (code === '00') {
      return data
    } else if (code === 'E000013') {
      /* JWT无效 */
      // if (window.loginPageUrl) {
      //   location = window.loginPageUrl
      // }
      Notification({
        title: '温馨提示',
        message: '登录过期，请重新登录',
        // type: 'info',
        duration: 2000
      })
      router.replace('/login')
      return Promise.reject(response)
    } else if (code === 'E000012') {
      if (process.env.NODE_ENV !== 'production') {
        // alert('token过期')
        debugger
      }
      // 已经是token过期重新请求了
      if (response.config.isExpireRequest) {
        return Promise.reject(response)
      }
      // code:E000012
      // msg:token过期
      // data: {}

      const token = data.data.accessToken
      sessionStorage.setItem('Authorization', token)
      // 重新请求
      const config = response.config
      config.headers.Authorization = token
      config.isExpireRequest = true
      return service(config)
    } else {
      Notification({
        title: '请求失败',
        message: data.msg,
        type: 'error',
        duration: 2000
      })
      return Promise.reject(data)
    }
  },
  error => {
    let message
    switch (error.response.status) {
      case 400:
        message = '错误请求'
        break
      case 401:
        message = '未授权'
        break
      case 403:
        message = '拒绝访问'
        break
      case 404:
        message = '请求路径未找到'
        break
      case 500:
        message = '服务器异常'
        break
      default:
        message = '未知错误'
    }
    // 避免出错提示多个、这样在页面上比较恶心
    if (!responseErrorNoticed) {
      responseErrorNoticed = Notification({
        title: '请求失败',
        message,
        type: 'warning',
        duration: 4000,
        onClose: () => {
          responseErrorNoticed = null
        }
      })
    }

    return Promise.reject(error)
  }
)

/**
 * 导出文件并保存
 * @param {object} axiosConfig axios的请求配置
 * @param {*} defaultFileName 文件名、默认的、后端有返回文件名的话会覆盖
 */
service.exportFileSave = function(axiosConfig, defaultFileName) {
  // const config = {
  //   url,
  //   type,
  //   payload,
  //   responseType: 'blob',
  //   timeout: 2 * 60 * 1000
  //   // onDownloadProgress: event => {
  //   //   console.log(' Progress: ', event)
  //   // }
  // }
  const config = {
    // 1s
    timeout: 60 * 1000,
    ...axiosConfig,
    responseType: 'blob'
  }
  return service(config)
    .then(res => {
      const { data } = res
      const fileName = res.fileName || defaultFileName
      return blobSaveFile(data, fileName)
    })
    .catch(() => {
      console.log('转换失败')
      Notification({
        title: '下载文件失败',
        message: '下载' + (defaultFileName || '文件') + '失败',
        type: 'error',
        duration: 2000
      })
    })
}

export default service
